﻿using System;
using System.Collections.Concurrent;
using SweeperPrototype.Business;
using SweeperPrototype.Business.Fields;

namespace SweeperPrototype.Objects
{
    public partial class ExposureMappingSubscription
    {

        private const int MAX_UPDATE_LOOKBACK = 50;
        private readonly ConcurrentQueue<ExposureMappingUpdate> m_UpdateStack;
        
        private readonly ExposureRIC m_ExposureRIC;
        private readonly EffectiveRIC m_EffectiveRIC;
        
        private ExposureMappingUpdate m_LastUpdate;

        public ExposureMappingSubscription(ExposureRIC exposure_ric, EffectiveRIC effective_ric )
        {
            m_ExposureRIC = exposure_ric;
            m_EffectiveRIC = effective_ric;
            m_UpdateStack = new ConcurrentQueue<ExposureMappingUpdate>();
        }

        public ExposureRIC ExposureRIC
        {
            get { return m_ExposureRIC; }
        }

        public EffectiveRIC EffectiveRIC
        {
            get { return m_EffectiveRIC; }
        }

        public Multiplier Multiplier
        {
            get { return m_LastUpdate != null ? m_LastUpdate.Multiplier : null ; }
        }

        public bool IsValid
        {
            get { return m_LastUpdate != null; }
        }

        public ExposureMappingUpdate LastUpdate
        {
            get { return m_LastUpdate; }
        }

        public void Update(ExposureMappingUpdate update)
        {

            ExposureMappingUpdate previous = m_LastUpdate;
            m_LastUpdate = update;
            m_UpdateStack.Enqueue(previous);

            Updated(this, previous, update);

            if (m_UpdateStack.Count > MAX_UPDATE_LOOKBACK)
            {
                ExposureMappingUpdate dequeued;
                while (m_UpdateStack.TryDequeue(out dequeued) == false) { }
            }
        }
        public event UpdateDelegate<ExposureMappingSubscription, ExposureMappingUpdate> Updated = delegate { };

        public class ExposureMappingUpdate
        {
            private readonly Multiplier m_Multiplier;
            private readonly Timestamp m_Timestamp;

            public ExposureMappingUpdate(Multiplier multiplier, Timestamp timestamp)
            {
                m_Multiplier = multiplier;
                m_Timestamp = timestamp;
            }

            public Multiplier Multiplier
            {
                get { return m_Multiplier; }
            }

            public Timestamp Timestamp
            {
                get { return m_Timestamp; }
            }
        }
    }


}